# -*- coding: utf-8 -*-
"""
压力测试配置文件

定义不同测试场景的配置参数，包括：
- 测试环境配置
- 用户行为配置
- 性能指标阈值
- 测试数据配置
"""

import os
from dataclasses import dataclass
from typing import Dict, List, Optional


@dataclass
class LoadTestConfig:
    """
    压力测试配置类
    """
    # 基础配置
    host: str = "http://localhost:8000"
    users: int = 50
    spawn_rate: int = 5
    run_time: str = "60s"
    
    # 性能阈值配置
    max_response_time: float = 2000.0  # 最大响应时间(ms)
    max_failure_rate: float = 0.05     # 最大失败率(5%)
    min_rps: float = 10.0              # 最小RPS
    
    # 测试数据配置
    test_data_size: int = 100          # 测试数据量
    cleanup_after_test: bool = True    # 测试后清理数据
    
    # 报告配置
    html_report: bool = True           # 生成HTML报告
    csv_report: bool = True            # 生成CSV报告
    report_dir: str = "reports/performance"


# 预定义测试场景配置
TEST_SCENARIOS = {
    "smoke": LoadTestConfig(
        users=5,
        spawn_rate=1,
        run_time="30s",
        max_response_time=1000.0,
        max_failure_rate=0.01
    ),
    
    "load": LoadTestConfig(
        users=50,
        spawn_rate=5,
        run_time="300s",
        max_response_time=2000.0,
        max_failure_rate=0.05
    ),
    
    "stress": LoadTestConfig(
        users=200,
        spawn_rate=20,
        run_time="600s",
        max_response_time=5000.0,
        max_failure_rate=0.10
    ),
    
    "spike": LoadTestConfig(
        users=500,
        spawn_rate=50,
        run_time="180s",
        max_response_time=10000.0,
        max_failure_rate=0.15
    ),
    
    "endurance": LoadTestConfig(
        users=100,
        spawn_rate=10,
        run_time="3600s",  # 1小时
        max_response_time=3000.0,
        max_failure_rate=0.05
    )
}


# 环境配置
ENVIRONMENT_CONFIGS = {
    "local": {
        "host": "http://localhost:8000",
        "description": "本地开发环境"
    },
    "dev": {
        "host": "http://dev-api.example.com",
        "description": "开发环境"
    },
    "staging": {
        "host": "http://staging-api.example.com",
        "description": "预发布环境"
    },
    "prod": {
        "host": "http://api.example.com",
        "description": "生产环境"
    }
}


# API接口权重配置
API_WEIGHTS = {
    "GET /": 10,           # 根路径 - 高频访问
    "GET /health": 8,     # 健康检查 - 高频访问
    "GET /users/": 5,     # 获取用户列表 - 中频访问
    "GET /users/{id}": 4, # 获取用户详情 - 中频访问
    "POST /users/": 3,    # 创建用户 - 低频访问
    "PUT /users/{id}": 2, # 更新用户 - 低频访问
    "DELETE /users/{id}": 1, # 删除用户 - 最低频访问
    "GET /invalid": 1     # 错误接口 - 测试用
}


# 用户行为配置
USER_BEHAVIOR_CONFIG = {
    "think_time": {
        "min": 1,  # 最小思考时间(秒)
        "max": 3   # 最大思考时间(秒)
    },
    "session_duration": {
        "min": 60,   # 最小会话时长(秒)
        "max": 300   # 最大会话时长(秒)
    },
    "user_types": {
        "regular": {
            "weight": 70,  # 普通用户占比70%
            "think_time_multiplier": 1.0
        },
        "power": {
            "weight": 20,  # 高级用户占比20%
            "think_time_multiplier": 0.5
        },
        "admin": {
            "weight": 10,  # 管理员用户占比10%
            "think_time_multiplier": 0.3
        }
    }
}


# 性能监控配置
PERFORMACE_MONITORING = {
    "response_time_percentiles": [50, 75, 90, 95, 99],
    "alert_thresholds": {
        "response_time_p95": 3000,  # P95响应时间阈值(ms)
        "error_rate": 0.05,         # 错误率阈值(5%)
        "rps_min": 10,              # 最小RPS
        "cpu_usage": 0.80,          # CPU使用率阈值(80%)
        "memory_usage": 0.85        # 内存使用率阈值(85%)
    },
    "metrics_collection_interval": 5  # 指标收集间隔(秒)
}


# 测试数据配置
TEST_DATA_CONFIG = {
    "users": {
        "count": 1000,
        "name_prefix": "test_user_",
        "email_domain": "example.com",
        "age_range": (18, 65)
    },
    "batch_size": 50,  # 批量操作大小
    "data_cleanup": {
        "enabled": True,
        "cleanup_interval": 300,  # 清理间隔(秒)
        "max_test_data_age": 3600  # 测试数据最大存活时间(秒)
    }
}


# 报告配置
REPORT_CONFIG = {
    "output_dir": "reports/performance",
    "formats": ["html", "csv", "json"],
    "include_charts": True,
    "chart_types": ["response_time", "rps", "error_rate", "user_count"],
    "auto_open_report": False,
    "report_retention_days": 30
}

# 测试模式配置
TESTING = os.getenv("TESTING", "false").lower() == "true"


def get_config(scenario: str = "load", environment: str = "local") -> LoadTestConfig:
    """
    获取指定场景和环境的配置
    
    Args:
        scenario: 测试场景名称
        environment: 环境名称
    
    Returns:
        LoadTestConfig: 配置对象
    """
    if scenario not in TEST_SCENARIOS:
        raise ValueError(f"未知的测试场景: {scenario}")
    
    if environment not in ENVIRONMENT_CONFIGS:
        raise ValueError(f"未知的环境: {environment}")
    
    config = TEST_SCENARIOS[scenario]
    config.host = ENVIRONMENT_CONFIGS[environment]["host"]
    
    return config


def get_environment_from_env() -> str:
    """
    从环境变量获取测试环境
    
    Returns:
        str: 环境名称
    """
    return os.getenv("TEST_ENV", "local")


def get_scenario_from_env() -> str:
    """
    从环境变量获取测试场景
    
    Returns:
        str: 场景名称
    """
    return os.getenv("TEST_SCENARIO", "load")


if __name__ == "__main__":
    # 配置文件测试
    print("压力测试配置")
    print("=" * 40)
    
    print("\n可用测试场景:")
    for scenario, config in TEST_SCENARIOS.items():
        print(f"  {scenario}: {config.users}用户, {config.run_time}, 最大响应时间{config.max_response_time}ms")
    
    print("\n可用环境:")
    for env, config in ENVIRONMENT_CONFIGS.items():
        print(f"  {env}: {config['host']} - {config['description']}")
    
    print("\n示例配置获取:")
    example_config = get_config("load", "local")
    print(f"  场景: load, 环境: local")
    print(f"  主机: {example_config.host}")
    print(f"  用户数: {example_config.users}")
    print(f"  运行时间: {example_config.run_time}")